<?php

define("PHP_KPAPI_VERSION", "0.1");
define("USER_AGENT", sprintf("KP-PHP-Binding-%s", PHP_KPAPI_VERSION));


define("DEV_KEY_HEADER","KP_DEV_KEY");
define("KP_AUTH_HEADER","Cookie");
define("USER_AGENT_HEADER", "User-Agent");
define("CONTENT_TYPE_HEADER", "Content-Type");
define("CONTENT_LENGTH_HEADER", "Content-Length");

/**
 * cUrl abstraction for KP API Access do not use this file directly.
 */
class KP_Http{
	
	public $uathToken;
	
	private $devKey;
		
	function __construct($devKey,$authToken=NULL){
		$this->devKey = $devKey;
		$this->authToken = $authToken;
	}
	
	function get($url){
		$curl = $this->createCurlBase($url);
	
		$raw_json = curl_exec($curl);
		
		curl_close($curl);
		return json_decode($raw_json, false);
	}

	function post($url,$data){
		$curl = $this->createCurlBase($url);	
		
		curl_setopt($curl,CURLOPT_POST,true);				
		curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($data));		
		
		//execute post
		$raw_json = curl_exec($curl);
				
		//close connection
		curl_close($curl);
		return json_decode($raw_json, false);
	}
	
	private function createCurlBase($url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl,CURLOPT_URL,$url);
			
		$headers = $this->createHeaders();
						
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		return $curl;
	}
	
	private function createHeaders(){
		$headers = array(
			USER_AGENT_HEADER.': '.USER_AGENT,
			CONTENT_TYPE_HEADER.': application/json',
			DEV_KEY_HEADER.': '.$this->devKey
		);

		if(isset($this->authToken)){
			$headers[] = KP_AUTH_HEADER.': kpc='.$this->authToken;
		}
		return $headers;
	}
}
?>
